package com.yc.jpyy.mobile.controller;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.yc.jpyy.base.bean.RestResponse;
import com.yc.jpyy.base.config.Config;
import com.yc.jpyy.base.controller.BaseController;
import com.yc.jpyy.base.util.CheckSumBuilder;
import com.yc.jpyy.common.Common;
import com.yc.jpyy.mobile.dao.BizDao;
import com.yc.jpyy.mobile.service.BizService;

@Controller
@RequestMapping(value = "/userregister")
public class UserRegisterInfo extends BaseController{
	@Autowired
	private BizService bizService;
	@Autowired
	private BizDao bizDao;
	private static Logger logger = LoggerFactory.getLogger(BaseController.class);
	
	/**
	 * 获取短信验证码
	 * 
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@SuppressWarnings("finally")
	@RequestMapping(value = "/getSmsCode", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
	public @ResponseBody String getSmsCode(HttpServletRequest request)throws UnsupportedEncodingException {
		
		RestResponse response = new RestResponse();
		request.setCharacterEncoding("UTF-8");
		
        try {
    		// 手机号
    		String mobilephone = request.getParameter("mobilephone");
    		if(mobilephone != null && !mobilephone.isEmpty()){
        		CloseableHttpClient httpclient = HttpClients.createDefault();
                HttpPost httpPost = new HttpPost(Config.getSendCodeServerUrl());
                String curTime = String.valueOf((new Date()).getTime() / 1000L);
                String Nonce =  String.valueOf(Math.abs(new Random().nextInt()));
                String checkSum = CheckSumBuilder.getCheckSum(Config.getSMSAPPSecret(), Nonce, curTime);

                // 设置请求的header
                httpPost.addHeader("AppKey", Config.getSMSAPPKey());
                httpPost.addHeader("Nonce", Nonce);
                httpPost.addHeader("CurTime", curTime);
                httpPost.addHeader("CheckSum", checkSum);
                httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

                // 设置请求的的参数，requestBody参数
                List<NameValuePair> nvps = new ArrayList<NameValuePair>();
                nvps.add(new BasicNameValuePair("mobile", mobilephone));
                nvps.add(new BasicNameValuePair("codeLen", Config.getCodelen()));
                httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
                // 执行请求
    			HttpResponse responses = httpclient.execute(httpPost);
    			String responseEntity = EntityUtils.toString(responses.getEntity(), "utf-8");
    			String code= JSON.parseObject(responseEntity).getString("obj");
    			response.setErrorcode(0);
				response.setData(code);
    		}else{
    			response.setErrorcode(1);
				response.setMessage("手机号不能为空...");
    		}
		} catch (Exception e) {
			logger.info("UserRegisterInfo:"+ e.toString());
			response.setReturnMsg(1,"获取验证码失败！");
		} finally {
			return response.toJSON();
		}
	}
	
	/*
	 * 验证手机验证码
	 */
	public String verifyCode(String userName,String code) throws ClientProtocolException, IOException{
		//验证验证码是否填写正确
		CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(Config.getVerifyCodeServerUrl());
        String curTime = String.valueOf((new Date()).getTime() / 1000L);
        String Nonce =  String.valueOf(Math.abs(new Random().nextInt()));
        String checkSum = CheckSumBuilder.getCheckSum(Config.getSMSAPPSecret(), 
        		Nonce, curTime);
        // 设置请求的header
        httpPost.addHeader("AppKey", Config.getSMSAPPKey());
        httpPost.addHeader("Nonce", Nonce);
        httpPost.addHeader("CurTime", curTime);
        httpPost.addHeader("CheckSum", checkSum);
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        
        // 设置请求的的参数，requestBody参数
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("mobile", userName));
        nvps.add(new BasicNameValuePair("code", code));

        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));

        // 执行请求
        HttpResponse responses = httpclient.execute(httpPost);
        String responseEntity = EntityUtils.toString(responses.getEntity(), "utf-8");
        String statusCode= JSON.parseObject(responseEntity).getString("code");
        return statusCode;
	}
	
	/**
	 * 注册用户
	 * 
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@SuppressWarnings("finally")
	@RequestMapping(value = "/UserRegisterInfo", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
	public @ResponseBody String userRegisterInfo(HttpServletRequest request)
			throws UnsupportedEncodingException {

		RestResponse response = new RestResponse();
		request.setCharacterEncoding("UTF-8");
		try {
			// 手机号
			String userName = request.getParameter("userName");
			// 密码
			String passWord = request.getParameter("passWord");
			//验证码
			//String code = request.getParameter("code");
			
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
			if(userName != null && !userName.isEmpty() 
					&& passWord != null && !passWord.isEmpty()){	
				Map<String, Object> valMap = new HashMap<String, Object>();
	        	valMap.put("createtime", df.format(new Date()));
				valMap.put("username", userName);
				valMap.put("account", String.valueOf(Math.random()).substring(2, 11));
				valMap.put("password", Common.genMDInfo(passWord));
				//头像默认路径
				String picPath = "";
				valMap.put("pic", picPath);
				//注册
				response = bizService.userRegister(valMap,response);
				//以下是包括检验验证码的业务逻辑，后来验证码功能直接放在APP端，不需要在此处理，所以注释掉
				/*if(code != null && !code.isEmpty()){
	               String statusCode= verifyCode(userName,code);
			        if (statusCode.equals("200")){
			        	Map<String, Object> valMap = new HashMap<String, Object>();
			        	valMap.put("createtime", df.format(new Date()));
						valMap.put("username", userName);
						valMap.put("password", Common.genMDInfo(passWord));
						//头像默认路径
						String picPath = "";
						valMap.put("pic", picPath);
						//注册
						response = bizService.userRegister(valMap,response);
			        }else{
			        	response.setErrorcode(1);
						response.setMessage("验证码错误...");
			        }
				}else{
					response.setErrorcode(1);
					response.setMessage("验证码不能为空...");
				}	*/
			}else{
				response.setErrorcode(1);
				response.setMessage("手机号或密码不能为空...");
			}
		} catch (Exception e) {
			logger.info("UserRegisterInfo:"+ e.toString());
			response.setReturnMsg(1,"注册失败！");
		} finally {
			return response.toJSON();
		}
	}
	
	/**
	 * 系统登录
	 * 
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@SuppressWarnings("finally")
	@RequestMapping(value = "/UserLogin", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
	public @ResponseBody String userLogin(HttpServletRequest request)
			throws UnsupportedEncodingException {

		RestResponse response = new RestResponse();
		request.setCharacterEncoding("UTF-8");

		try {

			// 手机号
			String userName = request.getParameter("userName");
			// 密码
			String passWord = request.getParameter("passWord");
			Map<String, Object> valMap = new HashMap<String, Object>();
			 
			if(userName != null && !userName.isEmpty() 
					&& passWord != null && !passWord.isEmpty()){
				valMap.put("imgUrl", Config.getImageAddress());
				valMap.put("username", userName);
				valMap.put("password", Common.genMDInfo(passWord));
				response = bizService.LoginSystemInfo(valMap,response);
			}else{
				response.setErrorcode(1);
				response.setMessage("手机号或密码不能为空...");
			}
		} catch (Exception e) {
			logger.info("UserLogin:"+ e.toString());
			response.setReturnMsg(1,"登录失败！");
		} finally {
			return response.toJSON();
		}
	}
	
	/**
	 * 绑定、解绑
	 * 
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@SuppressWarnings("finally")
	@RequestMapping(value = "/UserBind", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
	public @ResponseBody String userBind(HttpServletRequest request)
			throws UnsupportedEncodingException {

		RestResponse response = new RestResponse();
		request.setCharacterEncoding("UTF-8");

		try {
			// 手机号
			String username = request.getParameter("username");	 
			// 身份证号
			String idcardno = request.getParameter("idcardno"); 
			// 车型
			String driveTypeName = request.getParameter("driveTypeName"); 
			// 绑定类型 1 绑定  0 解绑
			String bindtype = request.getParameter("bindtype");
			
			Map<String, Object> valMap = new HashMap<String, Object>();
			if(username != null && !username.isEmpty() 
					&& idcardno != null && !idcardno.isEmpty()
					&& bindtype != null && !bindtype.isEmpty())
			{
				valMap.put("idcardno", idcardno);
				valMap.put("username", username);
				valMap.put("driveTypeName", driveTypeName);
				valMap.put("imgUrl", Config.getImageAddress());
				valMap.put("bindtype", bindtype);
				response = bizService.BIndOrNot(valMap,response);
			}else{
				response.setErrorcode(1);
				response.setMessage("手机号、身份证号或绑定类型不能为空...");
			}
		} catch (Exception e) {
			logger.info("UserBind:"+ e.toString());
			response.setReturnMsg(1,"操作失败！");
		} finally {
			return response.toJSON();
		}
	}
	
	/**
	 * 激活
	 */
	@SuppressWarnings("finally")
	@RequestMapping(value = "/activeStudent", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
	public @ResponseBody String activeStudent(HttpServletRequest request)
			throws UnsupportedEncodingException {

		RestResponse response = new RestResponse();
		request.setCharacterEncoding("UTF-8");

		try { 
			// 身份证号
			String idcardno = request.getParameter("idcardno"); 
			// 车型
			String driveTypeName = request.getParameter("driveTypeName"); 
			//激活码
			String registrationNumber = request.getParameter("registrationNumber"); 
			
			Map<String, Object> valMap = new HashMap<String, Object>();
			if(registrationNumber != null && !registrationNumber.isEmpty() 
					&& idcardno != null && !idcardno.isEmpty()){
				valMap.put("idcardno", idcardno);
				valMap.put("driveTypeName", driveTypeName);
				valMap.put("registrationNumber", registrationNumber);
				response = bizService.activeStudent(valMap,response);
			}else{
				response.setErrorcode(1);
				response.setMessage("身份证号或激活码不能为空...");
			}
		} catch (Exception e) {
			logger.info("activeStudent:"+ e.toString());
			response.setReturnMsg(1,"操作失败！");
		} finally {
			return response.toJSON();
		}
	}
	
	/*
	 * 忘记密码（更改密码）接口
	 */
	@SuppressWarnings("finally")
	@RequestMapping(value = "/forgetPassWord", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
	public @ResponseBody String forgetPassWord(HttpServletRequest request)
			throws UnsupportedEncodingException {

		RestResponse response = new RestResponse();
		request.setCharacterEncoding("UTF-8");
		
		try{
			// 手机号
			String mobilePhone = request.getParameter("mobilePhone");
			//重新设置的新密码
			String newsPwd = request.getParameter("newsPwd");
			//验证码
			//String code = request.getParameter("code");
			
			if(mobilePhone != null && !mobilePhone.isEmpty() && newsPwd != null && !newsPwd.isEmpty())
			{	
				//if(code != null && !code.isEmpty()){
	               // String statusCode= verifyCode(mobilePhone,code);
			       // if (statusCode.equals("200")){
			        	// 修改密码
						int i = bizService.updateStuPwd(Common.genMDInfo(newsPwd),mobilePhone);
						if (i == 0){
							response.setErrorcode(1);
							response.setMessage("密码修改失败！");
						}else{
							response.setErrorcode(0);
							response.setData(newsPwd);
						}
			        //}else{
			        	//response.setErrorcode(1);
						//response.setMessage("验证码错误...");			        	
			        //}
			     //}else{
			        //response.setErrorcode(1);
					//response.setMessage("验证码不能为空...");
			     //}
			}else{
		        response.setErrorcode(1);
				response.setMessage("手机号不能为空...");				
			}
		}catch(Exception e){
			logger.info("forgetPassWord:"+ e.toString());
			response.setReturnMsg(1,"操作失败！");
		}finally{
			return response.toJSON();
		}
	}
	
}
